/**
 * 模型发现状态管理 - 智能缓存和状态同步
 */
import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';
import modelDiscoveryService, { AvailableModel } from '@/services/model-discovery.service';
import { useModelConfigStore } from './model-config.store';

interface ModelDiscoveryState {
  // 状态
  availableModels: AvailableModel[];
  selectedModelId: string | null;
  loading: boolean;
  error: string | null;
  lastRefresh: Date | null;
  cacheExpiry: Date | null;
  
  // 统计信息
  statistics: {
    total: number;
    available: number;
    unavailable: number;
    checking: number;
    providers: Record<string, number>;
  } | null;
  
  // 网络状态
  isOnline: boolean;
  autoRefreshEnabled: boolean;
  refreshInterval: number; // 分钟
  
  // 操作方法
  loadModels: (forceRefresh?: boolean) => Promise<void>;
  refreshModels: () => Promise<void>;
  selectModel: (modelId: string) => void;
  searchModels: (query: string) => AvailableModel[];
  getModelsByProvider: (provider: string) => AvailableModel[];
  getOnlineModels: () => AvailableModel[];
  getRecommendedModels: () => AvailableModel[];
  updateModelStatus: (modelId: string, status: 'available' | 'unavailable' | 'checking') => void;
  setAutoRefresh: (enabled: boolean, interval?: number) => void;
  clearCache: () => void;
  clearError: () => void;
  syncWithModelConfig: () => Promise<void>;
  handleConfigChange: (configId: string, action: 'created' | 'updated' | 'deleted') => Promise<void>;
}

// 智能缓存策略
const CACHE_TTL = 15 * 60 * 1000; // 15分钟
const MIN_REFRESH_INTERVAL = 1 * 60 * 1000; // 最小刷新间隔1分钟

export const useModelDiscoveryStore = create<ModelDiscoveryState>()(
  devtools(
    persist(
      (set, get) => ({
        // 初始状态
        availableModels: [],
        selectedModelId: null,
        loading: false,
        error: null,
        lastRefresh: null,
        cacheExpiry: null,
        statistics: null,
        isOnline: navigator.onLine,
        autoRefreshEnabled: true,
        refreshInterval: 5, // 默认5分钟
        
        // 加载模型列表
        loadModels: async (forceRefresh = false) => {
          const state = get();
          
          // 检查缓存是否有效
          if (!forceRefresh && state.cacheExpiry && new Date() < state.cacheExpiry) {
            // 使用缓存数据
            return;
          }
          
          // 检查最小刷新间隔
          if (!forceRefresh && state.lastRefresh) {
            const timeSinceLastRefresh = Date.now() - state.lastRefresh.getTime();
            if (timeSinceLastRefresh < MIN_REFRESH_INTERVAL) {
              return; // 避免过于频繁的刷新
            }
          }
          
          set({ loading: true, error: null });
          
          try {
            const models = await modelDiscoveryService.getAvailableModels(forceRefresh);
            const statistics = await modelDiscoveryService.getModelStatistics();
            
            set({
              availableModels: models,
              statistics,
              lastRefresh: new Date(),
              cacheExpiry: new Date(Date.now() + CACHE_TTL),
              loading: false
            });
          } catch (error) {
            set({
              error: error instanceof Error ? error.message : '加载模型失败',
              loading: false
            });
            
            // 离线时使用缓存
            if (!navigator.onLine && state.availableModels.length > 0) {
              console.log('离线模式：使用缓存的模型数据');
            }
          }
        },
        
        // 刷新模型列表
        refreshModels: async () => {
          const state = get();
          await state.loadModels(true);
        },
        
        // 选择模型
        selectModel: (modelId: string) => {
          set({ selectedModelId: modelId });
        },
        
        // 搜索模型
        searchModels: (query: string) => {
          const state = get();
          const lowerQuery = query.toLowerCase();
          
          return state.availableModels.filter(model =>
            model.name.toLowerCase().includes(lowerQuery) ||
            model.displayName.toLowerCase().includes(lowerQuery) ||
            model.provider.toLowerCase().includes(lowerQuery) ||
            model.providerName.toLowerCase().includes(lowerQuery)
          );
        },
        
        // 按提供商获取模型
        getModelsByProvider: (provider: string) => {
          const state = get();
          return state.availableModels.filter(
            model => model.provider.toLowerCase() === provider.toLowerCase()
          );
        },
        
        // 获取在线模型
        getOnlineModels: () => {
          const state = get();
          return state.availableModels.filter(model => model.status === 'available');
        },
        
        // 获取推荐模型
        getRecommendedModels: () => {
          const state = get();
          return state.availableModels.filter(model => model.recommended);
        },
        
        // 更新模型状态
        updateModelStatus: (modelId: string, status: 'available' | 'unavailable' | 'checking') => {
          set((state) => ({
            availableModels: state.availableModels.map(model =>
              model.id === modelId ? { ...model, status } : model
            )
          }));
        },
        
        // 设置自动刷新
        setAutoRefresh: (enabled: boolean, interval?: number) => {
          set({
            autoRefreshEnabled: enabled,
            ...(interval && { refreshInterval: interval })
          });
        },
        
        // 清除缓存
        clearCache: () => {
          set({
            availableModels: [],
            cacheExpiry: null,
            lastRefresh: null,
            statistics: null
          });
        },
        
        // 清除错误
        clearError: () => {
          set({ error: null });
        },
        
        // 与模型配置同步
        syncWithModelConfig: async () => {
          try {
            // 强制刷新模型列表以获取最新配置
            await get().loadModels(true);
          } catch (error) {
            console.error('同步模型配置失败:', error);
          }
        },
        
        // 处理配置变更
        handleConfigChange: async (configId: string, action: 'created' | 'updated' | 'deleted') => {
          console.log(`配置变更: ${configId} - ${action}`);
          
          // 延迟刷新，确保配置变更已生效
          setTimeout(async () => {
            try {
              if (action === 'deleted') {
                // 移除对应的模型
                set((state) => ({
                  availableModels: state.availableModels.filter(
                    model => !model.id.includes(configId)
                  )
                }));
              } else {
                // 重新发现模型
                await get().loadModels(true);
              }
            } catch (error) {
              console.error('处理配置变更失败:', error);
            }
          }, 1000);
        }
      }),
      {
        name: 'model-discovery-storage',
        partialize: (state) => ({
          // 只持久化必要的数据
          availableModels: state.availableModels,
          selectedModelId: state.selectedModelId,
          lastRefresh: state.lastRefresh,
          cacheExpiry: state.cacheExpiry,
          statistics: state.statistics,
          autoRefreshEnabled: state.autoRefreshEnabled,
          refreshInterval: state.refreshInterval
        })
      }
    )
  )
);

// 监听网络状态变化
window.addEventListener('online', () => {
  const store = useModelDiscoveryStore.getState();
  store.refreshModels();
});

window.addEventListener('offline', () => {
  const store = useModelDiscoveryStore.getState();
  console.log('进入离线模式，使用缓存数据');
});

// 自动刷新定时器
let autoRefreshTimer: NodeJS.Timeout | null = null;

// 启动自动刷新
export const startAutoRefresh = () => {
  const store = useModelDiscoveryStore.getState();
  
  if (autoRefreshTimer) {
    clearInterval(autoRefreshTimer);
  }
  
  if (store.autoRefreshEnabled) {
    autoRefreshTimer = setInterval(() => {
      const currentStore = useModelDiscoveryStore.getState();
      if (currentStore.autoRefreshEnabled && navigator.onLine) {
        currentStore.loadModels(false);
      }
    }, store.refreshInterval * 60 * 1000);
  }
};

// 停止自动刷新
export const stopAutoRefresh = () => {
  if (autoRefreshTimer) {
    clearInterval(autoRefreshTimer);
    autoRefreshTimer = null;
  }
};

// 初始化时启动自动刷新
startAutoRefresh();

// 订阅状态变化以更新自动刷新
useModelDiscoveryStore.subscribe(
  (state) => ({ autoRefreshEnabled: state.autoRefreshEnabled, refreshInterval: state.refreshInterval }),
  (current, previous) => {
    if (current.autoRefreshEnabled !== previous.autoRefreshEnabled ||
        current.refreshInterval !== previous.refreshInterval) {
      startAutoRefresh();
    }
  }
);

// 监听模型配置变更事件
if (typeof window !== 'undefined') {
  // 监听来自配置管理界面的事件
  window.addEventListener('model-config-changed', ((event: CustomEvent) => {
    const { configId, action } = event.detail;
    const store = useModelDiscoveryStore.getState();
    store.handleConfigChange(configId, action);
  }) as EventListener);
  
  // 监听存储变更（跨标签页同步）
  window.addEventListener('storage', (event) => {
    if (event.key === 'model-config-storage') {
      const store = useModelDiscoveryStore.getState();
      store.syncWithModelConfig();
    }
  });
}